<template>
  <a-modal
    v-model:visible="visible"
    title="设备使用登记"
    :width="600"
    :mask-closable="false"
    :esc-to-close="false"
    :confirm-loading="loading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
      auto-label-width
    >
      <a-form-item label="设备名称" field="deviceName">
        <a-input v-model="formData.deviceName" disabled placeholder="设备名称" />
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="使用时间" field="useTime" required>
            <a-date-picker
              v-model="formData.useTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
              placeholder="请选择使用时间"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态" field="status" required>
            <a-select
              v-model="formData.status"
              :options="statusOptions"
              placeholder="请选择状态"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="使用位置" field="location" >
        <a-select
          v-model="formData.location"
          :options="locationOptions"
          placeholder="请选择使用位置"
          allow-search
          :field-names="{ value: 'id', label: 'name' }"
        >
          <template #option="{ data: { name, id } }">
            <span>{{ name }}</span>
          </template>
        </a-select>
      </a-form-item>

      <a-form-item label="使用任务" field="taskId">
        <a-select
          v-model="formData.taskId"
          :options="taskOptions"
          placeholder="请选择使用任务"
          allow-search
          allow-clear
          :field-names="{ value: 'id', label: 'name' }"
        >
          <template #option="{ data: { name, id } }">
            <span>{{ name }}</span>
          </template>
        </a-select>
      </a-form-item>

      <a-form-item label="使用人" field="userId" required>
        <a-select
          v-model="formData.userId"
          :options="userOptions"
          placeholder="请选择使用人"
          allow-search
          :field-names="{ value: 'id', label: 'nickname' }"
        >
          <template #option="{ data: { nickname, id } }">
            <span>{{ nickname }}</span>
          </template>
        </a-select>
      </a-form-item>

      <a-form-item label="备注" field="remark">
        <a-textarea
          v-model="formData.remark"
          placeholder="请输入备注信息"
          :max-length="200"
          show-word-limit
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { 
  DeviceCirculationRegisterReq, 
  UserOption, 
  TaskOption 
} from '@/apis/generator/deviceCirculation'
import type { LocationOption } from '@/apis/task/taskloc'
import { searchUsers, registerDevice, searchTasks } from '@/apis/generator/deviceCirculation'
import { searchLocs } from '@/apis/task/taskloc'

interface RegisterFormData extends Omit<DeviceCirculationRegisterReq, 'useTime'> {
  deviceName: string
  taskName: string
  useTime?: Date | string // 支持 Date 对象或格式化的字符串（YYYY-MM-DD HH:mm:ss）
  remark?: string
}

const visible = ref(false)
const formRef = ref()
const loading = ref(false)

const formData = reactive<RegisterFormData>({
  circulationId: '',
  deviceName: '',
  useTime: undefined,
  location: '',
  taskId: '',
  taskName: '',
  userId: '',
  status: 1, // 默认在用
  remark: ''
})

const userOptions = ref<UserOption[]>([])
const locationOptions = ref<LocationOption[]>([])
const taskOptions = ref<TaskOption[]>([])

const statusOptions = [
  { value: 1, label: '在用' },
  { value: 2, label: '外借' }
]

// 获取任务名称（用于显示）
const getTaskName = (taskId: string | number | null | undefined): string => {
  if (!taskId) return ''
  const task = taskOptions.value.find(t => String(t.id) === String(taskId) || t.id === taskId)
  return task ? task.name : String(taskId)
}

const rules = {
  useTime: [{ required: true, message: '请选择使用时间' }],
  userId: [{ required: true, message: '请选择使用人' }],
  status: [{ required: true, message: '请选择状态' }]
}

// 加载下拉数据
const loadSelectData = async () => {
  try {
    const [users, locs, tasks] = await Promise.all([
      searchUsers(),
      searchLocs(),
      searchTasks()
    ])
    userOptions.value = users
    locationOptions.value = locs
    taskOptions.value = tasks
  } catch (error) {
    console.error('加载下拉数据失败:', error)
    Message.error('加载数据失败，请刷新页面重试')
  }
}

// 打开模态框
const open = async (record: any) => {
  if (!record || !record.circulationId) {
    Message.error('设备记录信息不完整，无法登记')
    return
  }
  
  visible.value = true
  
  // 先加载下拉数据，确保所有选项可用
  await loadSelectData()
  
  // 获取设备对应的任务ID（兼容多种字段名和类型）
  const deviceTaskId = record.taskId || record.task_id || null
  const deviceTaskName = record.taskName || record.taskname || record.task_name || ''
  
  // 如果record中有任务名称但没有任务ID，尝试通过名称查找任务ID
  let finalTaskId: string | null = deviceTaskId ? String(deviceTaskId) : null
  if (!finalTaskId && deviceTaskName && taskOptions.value.length > 0) {
    const matchedTask = taskOptions.value.find(task => task.name === deviceTaskName)
    if (matchedTask) {
      finalTaskId = String(matchedTask.id)
    }
  }
  
  // 填充表单数据
  // 先设置taskId为null，后面会根据匹配结果设置正确的值
  let initialTaskId: string | null = null
  if (finalTaskId && taskOptions.value.length > 0) {
    // 查找匹配的任务，使用与options中相同的ID类型
    const matchedTask = taskOptions.value.find(task => {
      const taskIdStr = String(task.id)
      return taskIdStr === finalTaskId || task.id === finalTaskId
    })
    if (matchedTask) {
      // 使用与options中ID相同的类型
      initialTaskId = matchedTask.id as any
    }
  }
  
  // 格式化当前时间为 YYYY-MM-DD HH:mm:ss 格式（用于日期选择器）
  const now = new Date()
  const formattedNow = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
  
  Object.assign(formData, {
    circulationId: String(record.circulationId),
    deviceName: record.deviceName || '',
    taskId: initialTaskId || '',
    taskName: deviceTaskName,
    useTime: formattedNow, // 默认设置为当前时间（格式化为字符串，与日期选择器的 value-format 一致）
    location: record.location || '',
    userId: record.userId ? String(record.userId) : '',
    status: 1, // 默认在用
    remark: record.remark || ''
  })
  
  // 确保DOM更新，让select组件能正确显示
  await nextTick()
  
  // 如果已经有匹配的任务ID，再次验证确保正确显示
  if (formData.taskId && taskOptions.value.length > 0) {
    const currentTaskId = formData.taskId
    const taskExists = taskOptions.value.some(task => {
      return String(task.id) === String(currentTaskId) || task.id === currentTaskId
    })
    
    if (!taskExists) {
      // 如果任务ID不在选项中，清空taskId，让用户重新选择
      formData.taskId = ''
      console.warn('设备任务ID不在任务选项中，已清空:', {
        deviceTaskId: currentTaskId,
        deviceName: record.deviceName,
        availableTasks: taskOptions.value.map(t => ({ id: t.id, name: t.name }))
      })
    }
  }
}

// 确定提交
const handleOk = async () => {
  try {
    // 手动验证表单
    await formRef.value?.validate()
  } catch (error) {
    // 验证失败，直接返回
    return
  }

  try {
    loading.value = true
    
    // 格式化使用时间
    let useTimeStr: string
    if (formData.useTime) {
      if (formData.useTime instanceof Date) {
        // 将 Date 对象格式化为 YYYY-MM-DD HH:mm:ss 格式
        const year = formData.useTime.getFullYear()
        const month = String(formData.useTime.getMonth() + 1).padStart(2, '0')
        const day = String(formData.useTime.getDate()).padStart(2, '0')
        const hours = String(formData.useTime.getHours()).padStart(2, '0')
        const minutes = String(formData.useTime.getMinutes()).padStart(2, '0')
        const seconds = String(formData.useTime.getSeconds()).padStart(2, '0')
        useTimeStr = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      } else {
        // 如果已经是字符串格式，直接使用
        useTimeStr = formData.useTime
      }
    } else {
      // 如果没有选择时间，使用当前时间并格式化为 YYYY-MM-DD HH:mm:ss
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')
      useTimeStr = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
    
    const submitData: DeviceCirculationRegisterReq = {
      circulationId: formData.circulationId,
      useTime: useTimeStr,
      location: formData.location,
      userId: formData.userId,
      status: formData.status,
      deviceName: formData.deviceName,
      taskId: formData.taskId ? String(formData.taskId) : undefined // 如果为空字符串，转换为undefined
    }

    const res = await registerDevice(submitData)
    
    // 检查响应结果
    if (res && res.success === false) {
      const errorMsg = (res as any).data?.message || (res as any).message || res.msg || '使用登记失败'
      Message.error(errorMsg)
      return
    }
    
    Message.success((res as any)?.data?.message || (res as any)?.message || res?.msg || '使用登记成功')
    
    // 重置表单
    formRef.value?.resetFields()
    visible.value = false
    emit('save-success')
  } catch (error: any) {
    console.error('使用登记失败:', error)
    // 从错误对象中提取错误信息，优先使用 message 字段（后端返回的字段）
    const errorMsg = error?.message || error?.msg || error?.response?.data?.message || error?.response?.data?.msg || '使用登记失败，请重试'
    Message.error(errorMsg)
  } finally {
    loading.value = false
  }
}

// 取消
const handleCancel = () => {
  // 重置表单数据
  // 格式化当前时间为默认值
  const now = new Date()
  const formattedNow = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
  
  Object.assign(formData, {
    circulationId: '',
    deviceName: '',
    useTime: formattedNow, // 重置为当前时间（格式化为字符串）
    location: '',
    taskId: '',
    taskName: '',
    userId: '',
    status: 1, // 默认在用
    remark: ''
  })
  formRef.value?.resetFields()
  visible.value = false
}

const emit = defineEmits<{
  'save-success': []
}>()

defineExpose({
  open
})
</script>